import {createRouter, createWebHistory} from "vue-router";
import {getToken} from "@/api/cookie.js";
import {isTokenExpired} from "@/api/utils.js";
import {ElMessage} from "element-plus";

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/",
            redirect: "/admin/login"
        },
        {
            path: "/admin/login",
            component: () => import("@/components/views/Login.vue")
        },
        {
            path: "/admin/register",
            component: () => import("@/components/views/Register.vue")
        },
        {
            path: "/admin/system",
            component: () => import("@/components/views/System.vue"),
            children: [
                {
                    path: "user",
                    component: () => import("@/components/edits/User.vue")
                },
                {
                    path: "question",
                    component: () => import("@/components/edits/Question.vue")
                },
                {
                    path: "race",
                    component: () => import("@/components/edits/Race.vue"),

                },
                {
                    path: "updateRace",
                    component: () => import("@/components/edits/UpdateRace.vue")
                },
                {
                    path: "brush",
                    component: () => import("@/components/edits/Brush.vue")
                },
                {
                    path: "practice",
                    component: () => import("@/components/edits/Practice.vue")
                },
                {
                    path: "discuss",
                    component: () => import("@/components/edits/Discuss.vue")
                },
                {
                    path: "interview",
                    component: () => import("@/components/edits/Interview.vue")
                }
            ]
        },
        {
            path: "/:pathMatch(.*)*",
            name: "NotFound",
            component: () => import("@/components/views/404.vue"),
        }
    ]
})

router.beforeEach((to, from, next) => {
    const token = getToken()

    if (to.name === "NotFound") {
        next();
        return;
    }

    if (token && !isTokenExpired(token)) {
        // 此时有token && token 处于有效期
        if (to.path === '/admin/login') {
            // 这里如果访问 / 页面，会进行重定向到 /login 页面
            next({
                path: '/admin/system/user'
            })
        } else {
            // 访问其他页面，直接访问即可
            next()
        }
    } else {
        // 此时 token不存在 | token过期
        if (to.path !== '/admin/login') {
            ElMessage.error("用户登录信息已过期")
            // 重定向到 /login 页面
            next({
                path: '/admin/login'
            })
        } else {
            next()
        }
    }
})

export default router